﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HdipCricketClub.Models;
using HdipCricketClub.ViewModels;

namespace HdipCricketClub.Controllers
{
    public class ScorecardController : Controller
    {
        // database connection

        CricketClubEntities db = new CricketClubEntities();

        // database query repositories

        FixtureRepository fixtureRepository = new FixtureRepository();
        MemberRepository memberRepository = new MemberRepository();
        ClubFixturePlayerRepository clubFixturePlayerRepository = new ClubFixturePlayerRepository();
        ClubOtherFixtureDetailRepository clubOtherFixtureDetailRepository = new ClubOtherFixtureDetailRepository();
        OpponentFixturePlayerRepository opponentFixturePlayerRepository = new OpponentFixturePlayerRepository();
        OpponentOtherFixtureDetailRepository opponentOtherFixtureDetailRepository = new OpponentOtherFixtureDetailRepository();

        //
        // GET: /Scorecard/

        public ViewResult Index()
        {
            var fixtures = fixtureRepository.FindFixturesWithNoScoreCard();

            if (fixtures.Count() < 1)
            {
                ViewBag.Message = "There are no fixtures with scorecards to be entered";
            }

            return View(fixtures.ToList());
        }

        //
        // GET: /Scorecard/CreateTeam/

        public ActionResult CreateTeam(int id)
        {
            var fixture = fixtureRepository.GetFixture(id);

            if (ModelState.IsValid)
            {
                // create opponents team

                for (int i = 1; i <= fixture.no_of_players; i++)
                {
                    OpponentFixturePlayer opponentFixturePlayer = new OpponentFixturePlayer() { op_fixture_id = id, op_player_no = i };
                    db.OpponentFixturePlayers.AddObject(opponentFixturePlayer);
                    db.SaveChanges();
                }

                // create club other fixture details

                ClubOtherFixtureDetail clubOtherFixtureDetail = new ClubOtherFixtureDetail() { fixture_id = id };
                db.ClubOtherFixtureDetails.AddObject(clubOtherFixtureDetail);
                db.SaveChanges();

                // create opponent other fixture details

                OpponentOtherFixtureDetail opponentOtherFixtureDetail = new OpponentOtherFixtureDetail() { fixture_id = id };
                db.OpponentOtherFixtureDetails.AddObject(opponentOtherFixtureDetail);
                db.SaveChanges();

                return RedirectToAction("InputPlayers", new { id = fixture.fixture_id });
            }
            else
            {
                return View("Index");
            }
        }

        //
        // GET /Scorecard/InputPlayers/

        public ActionResult InputPlayers(int id)
        {
            var fixture = fixtureRepository.GetFixture(id);
            var opponentPlayers = opponentFixturePlayerRepository.GetOpponentPlayers(id);
            //var opponentPlayers = db.OpponentFixturePlayers.Where(op => op.op_fixture_id == id);

            ViewBag.Team = fixture.Team.name;
            ViewBag.OpponentClub = fixture.Opponent.club_name;
            ViewBag.OpponentTeam = fixture.Opponent.team_name;
            ViewBag.Date = fixture.date;
            ViewBag.Time = fixture.start_time;
            ViewBag.Venue = fixture.home;

            return View(opponentPlayers.ToList());
        }

        //
        //  POST /Scorecard/InputPlayers/

        [HttpPost]
        public ActionResult InputPlayers(FormCollection players)
        {
            if (ModelState.IsValid)
            {
                string[] formCollectionFixtureId = players.GetValues("item.op_fixture_id");
                string[] formCollectionPlayerNo = players.GetValues("item.op_player_no");
                string[] formCollectionPlayerName = players.GetValues("item.op_player_name");

                int currentFixtureId = Int32.Parse(formCollectionFixtureId[0]);

                for (int i = 0; i < formCollectionPlayerNo.Length; i++)
                {
                    OpponentFixturePlayer tempPlayer = new OpponentFixturePlayer();
                    tempPlayer.op_fixture_id = currentFixtureId;
                    tempPlayer.op_player_no = Int32.Parse(formCollectionPlayerNo[i]);

                    OpponentFixturePlayer currentPlayer = db.OpponentFixturePlayers.First(ofp => ofp.op_fixture_id == tempPlayer.op_fixture_id && ofp.op_player_no == tempPlayer.op_player_no);

                    currentPlayer.op_player_name = formCollectionPlayerName[i];
                    db.ObjectStateManager.ChangeObjectState(currentPlayer, EntityState.Modified);
                    db.SaveChanges();
                }

                return RedirectToAction("ConfirmInput", new { id = currentFixtureId });
            }
            return View();
        }

        //
        //  GET:  /Scorecard/ConfirmInput/

        public ActionResult ConfirmInput(int id)
        {
            var fixture = fixtureRepository.GetFixture(id);

            var opponentFixturePlayers = opponentFixturePlayerRepository.GetOpponentPlayers(id);

            ViewBag.fixtureId = fixture.fixture_id;

            return View(opponentFixturePlayers.ToList());
        }

        //
        //  GET: /Scorecard/WhoBattedFirst/

        public ActionResult WhoBattedFirst(int id)
        {
            Fixture fixture = fixtureRepository.GetFixture(id);

            return View(fixture);
        }

        //
        //  POST: /Scorecard/WhoBattedFirst/

        [HttpPost]
        public ActionResult WhoBattedFirst(Fixture fixture)
        {
            if (ModelState.IsValid)
            {
                db.Fixtures.Attach(fixture);
                db.ObjectStateManager.ChangeObjectState(fixture, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("inputData", new { id = fixture.fixture_id });
            }
            return View();
        }

        //
        // GET: Scorecard/Confirm/

        public ActionResult Confirm()
        {
            return View();
        }

        //
        // GET:  Scorecard/InputData/

        public ActionResult InputData(int id)
        {
            ScorecardViewModel scorecardViewModel = new ScorecardViewModel();

            scorecardViewModel.fixture = fixtureRepository.GetFixture(id);
            scorecardViewModel.clubFixturePlayer = clubFixturePlayerRepository.GetPlayers(id);
            scorecardViewModel.clubOtherFixtureDetail = clubOtherFixtureDetailRepository.GetClubOtherFixtureDetails(id);
            scorecardViewModel.opponentFixturePlayer = opponentFixturePlayerRepository.GetOpponentPlayers(id);
            scorecardViewModel.opponentOtherFixtureDetail = opponentOtherFixtureDetailRepository.GetOpponentOtherFixtureDetails(id);
            
            var player_id = db.ClubFixturePlayers.Include("Fixture").Include("Member").Include("DismissalType")
                                                                    .Where(cft => cft.fixture_id == id).ToList().AsQueryable();

            var op_player_no = db.OpponentFixturePlayers.Where(ofp => ofp.op_fixture_id == id);
            var dismissal_id = db.DismissalTypes.Select(dt => dt).ToList();
            var op_dismissal_id = dismissal_id;

            ViewBag.player_id = new SelectList(player_id, "player_id", "Member.InitialAndLastName");
            ViewBag.fielder_id = new SelectList(player_id, "player_id", "Member.InitialAndLastName");
            ViewBag.bowler_id = new SelectList(player_id, "player_id", "Member.InitialAndLastName");
            ViewBag.dismissal_id = new SelectList(dismissal_id, "dismissal_id", "type");

            ViewBag.op_player_no = new SelectList(op_player_no, "op_player_no", "op_player_name");
            ViewBag.op_dismissal_id = new SelectList(op_dismissal_id, "dismissal_id", "type");
            //ViewBag.op_fielder_no = new SelectList(op_player_no, "op_player_no", "op_player_name");
            //ViewBag.op_bowler_no = new SelectList(op_player_no, "op_player_no", "op_player_name");


            ViewBag.op_fielder_name = new SelectList(op_player_no, "op_player_name", "op_player_name");
            ViewBag.op_bowler_name = new SelectList(op_player_no, "op_player_name", "op_player_name");


            ViewBag.Team = scorecardViewModel.fixture.Team.name;
            ViewBag.OpponentClub = scorecardViewModel.fixture.Opponent.club_name;
            ViewBag.OpponentTeam = scorecardViewModel.fixture.Opponent.team_name;
            ViewBag.Date = scorecardViewModel.fixture.date;
            ViewBag.BattedFirst = scorecardViewModel.fixture.batted_first;

            return View(scorecardViewModel);
        }

        //
        // POST:  Scorecard/InputData/

        [HttpPost]
        public ActionResult InputData(FormCollection scorecard)
        {
            if (ModelState.IsValid)
            {
                //
                //  Get current fixture

                Fixture currentFixture = fixtureRepository.GetScoreCardFixtureId(scorecard);

                //
                //  Update club fixture players records

                ClubFixturePlayer clubFixturePlayer = new ClubFixturePlayer();
                clubFixturePlayer.UpdateClubFixturePlayerRecords(scorecard, currentFixture);
                double totalClubBatsmansRuns = clubFixturePlayerRepository.TotalBatsmensRuns(currentFixture.fixture_id);
                ViewBag.SubTotalBatsmen = totalClubBatsmansRuns;

                //
                //  Update club other fixture details

                ClubOtherFixtureDetail clubOtherFixtureDetail = new ClubOtherFixtureDetail();
                clubOtherFixtureDetail.UpdateClubOtherFixtureDetails(scorecard, currentFixture);
                double clubTotalExtras = clubOtherFixtureDetailRepository.ClubTotalExtras(currentFixture.fixture_id);
                ViewBag.ClubTotalExtras = clubTotalExtras;
                ViewBag.ClubTotal = totalClubBatsmansRuns + clubTotalExtras;

                //
                //  Update opponent player records

                OpponentFixturePlayer opponentFixturePlayer = new OpponentFixturePlayer();
                opponentFixturePlayer.UpdateOpponentFixturePlayerRecords(scorecard, currentFixture);
                double totalOpponentBatsmansRuns = opponentFixturePlayerRepository.TotalOpponentBatsmensRuns(currentFixture.fixture_id);
                ViewBag.SubTotalOpponentBatsmen = totalOpponentBatsmansRuns;

                //  Update opponent other fixture details

                OpponentOtherFixtureDetail opponentOtherFixtureDetail = new OpponentOtherFixtureDetail();
                opponentOtherFixtureDetail.UpdateOpponentOtherFixtureDetails(scorecard, currentFixture);
                double opponentTotalExtras = opponentOtherFixtureDetailRepository.OpponentTotalExtras(currentFixture.fixture_id);
                ViewBag.OpponentTotalExtras = opponentTotalExtras;
                ViewBag.OpponentTotal = totalOpponentBatsmansRuns + opponentTotalExtras;

                //
                //  Update club player season statistics 

                PlayerSeasonStatistic clubPlayerSeasonStatistics = new PlayerSeasonStatistic();
                clubPlayerSeasonStatistics.UpdateClubPlayerSeasonStatistics(scorecard, currentFixture);

                //
                // Update scorecard entered flag

                Fixture fixtureToUpdate = db.Fixtures.Where(f => f.fixture_id == currentFixture.fixture_id).Single();

                fixtureToUpdate.scorecard_entered = true;

                db.ObjectStateManager.ChangeObjectState(fixtureToUpdate, EntityState.Modified);
                db.SaveChanges();

                // Redirect to scorecard view
                
                return RedirectToAction("ShowScorecard", new { id = currentFixture.fixture_id });
            }
            return View();
        }

        //
        //  GET: Scorecard/ShowScorecard/

        public ActionResult ShowScoreCard(int id)
        {
            // create view model

            CompletedScoreCardViewModel completedScorecardViewModel = new CompletedScoreCardViewModel();

            // populate view model

            completedScorecardViewModel.CurrentFixture = fixtureRepository.GetFixture(id);
            completedScorecardViewModel.ClubBatsmen = clubFixturePlayerRepository.GetClubBatsman(id);
            completedScorecardViewModel.ClubBowlers = clubFixturePlayerRepository.GetClubBowlers(id);
            completedScorecardViewModel.ClubOtherDetails = clubOtherFixtureDetailRepository.GetClubOtherFixtureDetails(id);
            completedScorecardViewModel.OpponentBatsmen = opponentFixturePlayerRepository.GetOpponentBatsmen(id);
            completedScorecardViewModel.OpponentBowlers = opponentFixturePlayerRepository.GetOpponentBowlers(id);
            completedScorecardViewModel.OpponentOtherDetail = opponentOtherFixtureDetailRepository.GetOpponentOtherFixtureDetails(id);

            // populate club Viewbag items

            double subTotalClubBatsmensRuns = clubFixturePlayerRepository.TotalBatsmensRuns(id);
            ViewBag.SubTotalClubBatsmanRuns = subTotalClubBatsmensRuns;
            double clubTotalExtras = clubOtherFixtureDetailRepository.ClubTotalExtras(id);
            ViewBag.ClubTotalExtras = clubTotalExtras;
            double clubTotalRuns = subTotalClubBatsmensRuns + clubTotalExtras;
            ViewBag.ClubTotal = clubTotalRuns;

            // populate opponent Viewbag items

            double subTotalOpponentBatsmensRuns = opponentFixturePlayerRepository.TotalOpponentBatsmensRuns(id);
            ViewBag.SubTotalOpponentBatsmensRuns = subTotalOpponentBatsmensRuns;
            double opponentTotalExtras = opponentOtherFixtureDetailRepository.OpponentTotalExtras(id);
            ViewBag.OpponentTotalExtras = opponentTotalExtras;
            double opponentTotalRuns = subTotalOpponentBatsmensRuns + opponentTotalExtras;
            ViewBag.OpponentTotal = subTotalOpponentBatsmensRuns + opponentTotalExtras;

            return View(completedScorecardViewModel);

        }

        //
        //  GET: /Scorecard/EditScorecard/

        public ActionResult EditScorecard()
        {
            return View();
        }

        //
        // GET: /Scorecard/Details/5

        //public ViewResult Details(int id)
        //{
        //    ClubFixturePlayer clubfixtureplayer = db.ClubFixturePlayers.Single(c => c.fixture_id == id);
        //    return View(clubfixtureplayer);
        //}

        //
        // GET: /Scorecard/Create

        //public ActionResult Create()
        //{
        //    ViewBag.fixture_id = new SelectList(db.Fixtures, "fixture_id", "type");
        //    ViewBag.player_id = new SelectList(db.Members, "member_id", "first_name");
        //    ViewBag.how_out = new SelectList(db.DismissalTypes, "dismissal_id", "type");
        //    return View();
        //}

        ////
        //// POST: /Scorecard/Create

        //[HttpPost]
        //public ActionResult Create(ClubFixturePlayer clubfixtureplayer)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        db.ClubFixturePlayers.AddObject(clubfixtureplayer);
        //        db.SaveChanges();
        //        return RedirectToAction("Index");
        //    }

        //    ViewBag.fixture_id = new SelectList(db.Fixtures, "fixture_id", "type", clubfixtureplayer.fixture_id);
        //    ViewBag.player_id = new SelectList(db.Members, "member_id", "first_name", clubfixtureplayer.player_id);
        //    ViewBag.how_out = new SelectList(db.DismissalTypes, "dismissal_id", "type", clubfixtureplayer.how_out);
        //    return View(clubfixtureplayer);
        //}

        //
        // GET: /Scorecard/Edit/5

        //public ActionResult Edit(int id)
        //{
        //    ClubFixturePlayer clubfixtureplayer = db.ClubFixturePlayers.Single(c => c.fixture_id == id);
        //    ViewBag.fixture_id = new SelectList(db.Fixtures, "fixture_id", "type", clubfixtureplayer.fixture_id);
        //    ViewBag.player_id = new SelectList(db.Members, "member_id", "first_name", clubfixtureplayer.player_id);
        //    ViewBag.how_out = new SelectList(db.DismissalTypes, "dismissal_id", "type", clubfixtureplayer.how_out);
        //    return View(clubfixtureplayer);
        //}

        ////
        //// POST: /Scorecard/Edit/5

        //[HttpPost]
        //public ActionResult Edit(ClubFixturePlayer clubfixtureplayer)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        db.ClubFixturePlayers.Attach(clubfixtureplayer);
        //        db.ObjectStateManager.ChangeObjectState(clubfixtureplayer, EntityState.Modified);
        //        db.SaveChanges();
        //        return RedirectToAction("Index");
        //    }
        //    ViewBag.fixture_id = new SelectList(db.Fixtures, "fixture_id", "type", clubfixtureplayer.fixture_id);
        //    ViewBag.player_id = new SelectList(db.Members, "member_id", "first_name", clubfixtureplayer.player_id);
        //    ViewBag.how_out = new SelectList(db.DismissalTypes, "dismissal_id", "type", clubfixtureplayer.how_out);
        //    return View(clubfixtureplayer);
        //}

        ////
        //// GET: /Scorecard/Delete/5

        //public ActionResult Delete(int id)
        //{
        //    ClubFixturePlayer clubfixtureplayer = db.ClubFixturePlayers.Single(c => c.fixture_id == id);
        //    return View(clubfixtureplayer);
        //}

        ////
        //// POST: /Scorecard/Delete/5

        //[HttpPost, ActionName("Delete")]
        //public ActionResult DeleteConfirmed(int id)
        //{
        //    ClubFixturePlayer clubfixtureplayer = db.ClubFixturePlayers.Single(c => c.fixture_id == id);
        //    db.ClubFixturePlayers.DeleteObject(clubfixtureplayer);
        //    db.SaveChanges();
        //    return RedirectToAction("Index");
        //}

        //protected override void Dispose(bool disposing)
        //{
        //    db.Dispose();
        //    base.Dispose(disposing);
        //}
    }
}